<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>

        function findSourceId(arr, targetId) {
            let currentId = targetId;
            while (true) {
                let found = false;
                for (let i = 0; i < arr.length; i++) {
                    if (arr[i][1] === currentId) {
                        currentId = arr[i][0];
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    break;
                }
            }
            return currentId;
        }
        let arr1 = [[1, 2], [2, 3], [3, 4], [3, 5], [2, 6], [5, 7], [10, 11], [12, 13], [10, 14], [13, 15], [14, 16]];
        // 示例用法
        console.log(findSourceId(arr1, 5));  // 输出 1
        // console.log(findSourceId(arr1, 15)); // 输出 12
        // console.log(findSourceId(arr1, 16)); // 输出 10


        function findSourceIdRecursive(arr, currentId) {
            const matchingEntry = arr.find(entry => entry[1] === currentId);

            if (matchingEntry) {
                return findSourceIdRecursive(arr, matchingEntry[0]);
            }

            return currentId;
        }

        let arr2 = [[1, 2], [2, 3], [3, 4], [3, 5], [2, 6], [5, 7], [10, 11], [12, 13], [10, 14], [13, 15], [14, 16]];

        // 示例用法
        console.log(findSourceIdRecursive(arr2, 5));  // 输出 1
        console.log(findSourceIdRecursive(arr2, 15)); // 输出 12
        console.log(findSourceIdRecursive(arr2, 16)); // 输出 10


    </script>
</body>

</html>